<template>
  <el-dialog
    :append-to-body="true"
    @close="closeDialog"
    :visible.sync="dialog"
    :title="is_edit?'编辑Banner':'添加Banner'"
    width="500px"
  >
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="图片" prop="url">
        <el-upload
          class="upload-demo"
          action="http://server.shudais.com:8000/api/pictures"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :before-upload="beforeUpload"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="handleSuccess"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">请上传jpg/png文件，不大于500kb(尺寸：42)</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input placeholder="输入标题" v-model="form.title" style="width: 370px;" maxlength="20" />
      </el-form-item>
     <!-- <el-form-item label="跳转链接">
        <el-input placeholder="输入跳转链接" v-model="form.redirectTo" style="width: 370px;" maxlength="100" />
      </el-form-item>-->
      <el-form-item label="排序" prop="sort">
        <el-input placeholder="排序，请填数字1，2，3，4..." v-model="form.sort" style="width: 370px;" maxlength="4" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" size="mini" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { _bannerCreate, _bannerUpdate } from "@/http/ajax";
export default {
  name: "edit",
  props: {
    is_edit: {
      type: Boolean,
      required: true
    },
    cur_this: {
      type: Object,
      required: null
    }
  },
  data() {
     const validPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("排序值不能为空"));
      } else if (!this.isvalidCode(value)) {
        callback(new Error("排序值格式不对（只能是正整数）"));
      } else {
        callback();
      }
    };
    return {
      dialog: false,
      loading: false,
      form: {
        name: "",
        url: "",
        redirectTo: "",
        sort: "",
        status: 1,
        title: ""
      },
      fileList: [],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        url: [{ required: true, message: "请上传banner", trigger: "blur" }],
        sort: [{ required: true, validator: validPass, trigger: "blur" }]
      }
    };
  },
  created(){
  },
  methods: {
     isvalidCode(str) {
      const reg =/^[0-9]*[1-9][0-9]*$/;
      return reg.test(str);
    },
    doSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.sort>0){
            if (this.is_edit) {
              _bannerUpdate(
                this.form,
                res => {
                   this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                  this.dialog = false;
                 this.cur_this.getList()
                 this.dataInit()
                },
                err => {}
              );
            } else {
              _bannerCreate(
                this.form,
                res => {
                   this.$message({
                    message: "操作成功",
                    type: "success"
                  });
                  this.dialog = false;
                   this.cur_this.getList()
                   this.dataInit();
                },
                err => {}
              );
            }

          }else{
             this.$message({
              message: "请输入正确的排序值",
              type: "warning"
            });
          }
        }
      });
    },
    dataInit(){
       this.form = {
        name: "",
        url: "",
        redirectTo: "",
        sort: "",
        status: 1,
        title: ""
      };
      this.fileList = [];
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "jpg";
      const extension2 = testmsg === "png";
      const isLt2M = file.size / 1024 < 500
      console.log(file.size / 1024<500)
      console.log(extension || extension2 && isLt2M)
      if (!extension && !extension2) {
        this.$message({
          message: "上传图片只能是 jpg/png格式!",
          type: "warning"
        });
      }
      if(!isLt2M) {
          this.$message({
              message: '上传图片大小不能超过 500kb!',
              type: 'warning'
          });
      }
      return (extension || extension2) && isLt2M
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
       this.form["url"] = '';
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片");
    },
    beforeRemove(file, fileList) {
      console.log(file)
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, file, fileList) {
      this.form["url"] = response.data[0];
    },
    closeDialog() {
      this.fileList = [];
       this.$refs["form"].resetFields();
    }
  }
};
</script>

<style lang="scss">
</style>
